package cn.com.ethos.search.index;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.lucene.document.Document;

import cn.com.ethos.search.DbSetting;
import cn.com.ethos.search.ParametersHelper;

public class GenericDbRowStream extends DbRowStream {

	private Select select;
	
	public GenericDbRowStream(DbSetting settings,Select select) {
		super(settings);
		this.select = select;
	}

	@Override
	protected Document getDocument(ResultSet cursor) throws SQLException {
		Document doc = new Document();
		for(Field item : this.select.getFields()) {
			String name  = item.getName();
			String value = cursor.getString(name);			
			org.apache.lucene.document.Field fld = new org.apache.lucene.document.Field(name,value,item.getStore(),item.getIndex());
			fld.setBoost(item.getBoost());
			doc.add(fld);
		}
		if(this.select.getParameterKey().length() != 0) {
			this.select.setParameterValue(cursor.getString(this.select.getParameterKey()));
		}
		return doc;
	}

	@Override
	protected String getQuerySql() {
		return this.select.getSql();
	}	
	
	public void close() {
		super.close();
		
		if(this.select.getParameterKey().length() > 0) {
			String key   = this.select.getParameterHashKey();
			String value = this.select.getParameterValue();
			ParametersHelper.setParam(key, value);
			
			try {
				ParametersHelper.save();
			} catch (Exception ex){
				/***/
				System.err.println("Saving parameter failed");
			}			
		}	
	}
	
}
